package com.xsf.pay.common.filter;


import com.xsf.pay.common.domain.Rc;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @description: 自定义过滤器跨域配置
 * @date: 2020/01/01
 * @author: misker
 */
@Component
public class CorsFilters implements Filter {
    /**
     * 忽略权限检查的url地址
     */
    private final String[] excludeUrls = new String[]{};

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    private static final String ALLOWED_HEADERS = "x-requested-with, authorization, content-Type, credential, X-XSRF-TOKEN,token,username,client,timestamp,sign,responseType";
    private static final String CONT_TYPR_JSON  = "application/json";

    private static final String ALLOWED_METHODS = "*";
    private static final String ALLOWED_ORIGIN = "*";
    private static final String ALLOWED_EXPOSE = "*";
    private static final String MAX_AGE = "3600";

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取请求你ip后的全部路径
        String uri = request.getRequestURI();
        //跳过不需要的Xss校验的地址
        for (String str : excludeUrls) {
            if (uri.contains(str)) {
                filterChain.doFilter(servletRequest, response);
                return;
            }
        }
        response.setHeader("Access-Control-Allow-Origin", ALLOWED_ORIGIN);
        response.setHeader("Access-Control-Allow-Methods", ALLOWED_METHODS);
        response.setHeader("Access-Control-Max-Age", MAX_AGE);
        response.setHeader("Access-Control-Allow-Headers", ALLOWED_HEADERS);
        //如果是POST走自己的继承的HttpServletRequestWrapper类请求，否则走正常的请求
//        if(!ServletFileUpload.isMultipartContent(new Rc(request)) && StringUtil.stringEquels(HttpMethod.POST.name(), request.getMethod()) && CONT_TYPR_JSON.equals(request.getContentType())){
        //除了文件上传 其余走拦截
        if(!ServletFileUpload.isMultipartContent(new Rc(request))){
            //一定要在判断中new对象，否则还会出现Stream closed问题
            filterChain.doFilter(new AccessRequestWrapper(request),servletResponse);
        }else{
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }

    @Override
    public void destroy() {

    }


}
